import Path from "path";
import fs from "fs";

function getController(intoPath) {
    const filepath = path.join('../', intoPath);

    if (fs.existsSync(filepath)) {
        // Retrieve directory file (js)
        const files = fs.readdirSync(filepath).filter((file) => file.endsWith("js"));

        // Splicing the complete path together
        const fullPath = files.map((file) => {
            return `${Path.join(filepath, file)}`;
        });

        // Return the JS file path
        return fullPath;
    }
    // The path does not exist and returns null
    return null;
}

function registryRouter(router, controllersfullPath) {
    if (controllersfullPath === null) {
        return '无效路径';
    } else {
        // 遍历控制文件
        controllersfullPath.forEach(async (controller) => {
            // 导入控制文件
            const controllerUser = (await import(controller)).users;

            // 遍历配置路由（路径、方法、异步函数）
            for (const key in controllerUser) {
                // 获取 请求方法，请求路径
                const [requestMethod, requestPath] = key.split(" ");
                // 获取 请求函数
                const requestFn = controllerUser[key];

                // 验证请求方式
                if (requestMethod.endsWith("get")) {
                    // 处理 get 请求路由
                    router.get(requestPath, requestFn);
                } else if (requestMethod.endsWith("post")) {
                    // 处理 post 请求路由
                    router.post(requestPath, requestFn);
                } else {
                    // 请求方式不正确
                    console.log(`${requestMethod}：请求方式不正确`);
                }
            }
        });

    }


}

export const getController = getController;
export const registryRouters = registryRouter;